# -*- coding: utf-8 -*-
"""
Created on 2018 3.30
@author: hugh
"""

import config
import time
from load_image import LoadImage
from sklearn import metrics  
from sklearn.externals import joblib
from sklearn.neighbors import KNeighborsClassifier


def train(train_data, train_label, test_data, 
			test_label, model_check_point=config.model_check_point):
	"""KNN训练函数
	训练好的模型保存至model_check_point
	Args：
		train_data:
		train_label:
		test_data:
		test_label:
		model_check_point:
	"""	
	# KNN分类器，默认的n_neighbors参数为5  
	model = KNeighborsClassifier()
	#开始训练
	model.fit(train_data, train_label)
	#对训练集计算准确度
	train_accuracy = model.score(train_data, train_label)
	print ('train accuracy: %.2f%%' % (100 * train_accuracy)  )
	#对测试集计算准确度
	test_accuracy =  model.score(test_data, test_label)
	print ('test accuracy: %.2f%%' % (100 * test_accuracy))
	#保存训练好的模型
	joblib.dump(model, model_check_point)
	print("Model saved at:{}".format(model_check_point))


if __name__ == '__main__':
	start = time.time()
	print ("-----------------------------load_image start---------------------")
	# 准备训练数据，抽取人脸特征向量和标签组成训练数据
	all_image = LoadImage(config.data_dir)
	# 划分出训练集和测试集
	train_data, test_data, train_label, test_label= all_image.get_train_test_data()
	image_n = all_image.num_train_face
	# 样本的总数量
	print ("训练脸部样本的总数量:{}".format(image_n))	
	print ("-----------------------------trainning start------------------------")
	# 训练、测试并保存模型
	train(train_data, train_label, test_data, test_label)	
	# 计算数据预处理、训练、测试、保存的总耗时
	end = time.time()
	print("Trainning end. Elapsed time:{}".format(end-start))